package com.zlx.mall.basic.util;

import cn.hutool.core.date.DateUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author xiatian
 * @Date 2024/6/13 星期四 14:41
 * @注释
 */
@Component
public class GuidUtil {
    public static Long datetime = DateUtil.endOfDay(new Date()).getTime(); //DateUtil.getEndTime(System.currentTimeMillis());
    @Resource
    private RedisTemplate redisTemplate;

    public GuidUtil() {
    }

    public String createUid(String head, String platform, String key) {
        String oldKey = key + ":" + DateUtil.format(DateUtil.date(), "yyyyMMdd"); //DateUtil.format_yyyyMMdd(new Date(datetime));
        String newKey = "";
        long num = 1L;

        try {
            if (DateUtil.date().getTime() > datetime) {
                datetime = DateUtil.endOfDay(new Date()).getTime();
                if (this.redisTemplate.hasKey(oldKey)) {
                    redisTemplate.delete(new String[]{oldKey});
                }

                newKey = key + ":" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
            } else {
                newKey = oldKey;
            }
            num = redisTemplate.opsForValue().increment(newKey, 1L);
        } catch (Exception var9) {
            Exception e = var9;
            e.printStackTrace();
        }
        return head + platform + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + String.format("%06d", num);
    }
}

